﻿using System;
using System.Web;
using System.Web.Configuration;

namespace Web.Infrastructure.Mvc.HttpModules
{
    public class ActionNotFoundModule : IHttpModule
    {
        public void Dispose()
        {
            //nothing to du
        }

        public void Init(HttpApplication context)
        {
            context.Error += new EventHandler(ContextError);
        }

        private void ContextError(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication)sender).Context;
            if ((object.ReferenceEquals(context.Error.GetType(), typeof(HttpException))))
            {
                // Get the Web application configuration.
                System.Configuration.Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~/web.config");
                // Get the section.
                CustomErrorsSection customErrorsSection = (CustomErrorsSection)configuration.GetSection("system.web/customErrors");
                // Get the collection
                CustomErrorCollection customErrorsCollection = customErrorsSection.Errors;
                int statusCode = ((HttpException)context.Error).GetHttpCode();

                //Clears existing response headers and sets the desired ones.
                context.Response.ClearHeaders();
                context.Response.StatusCode = statusCode;

                if ((customErrorsCollection.Get(statusCode.ToString()) != null))
                {
                    var path = customErrorsCollection.Get(statusCode.ToString()).Redirect;
                    context.Server.TransferRequest(path, true);
                }
                else
                {
                    context.Response.Flush();
                }
            }
        }
    }
}